package cn.et.test;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wltea.analyzer.lucene.IKAnalyzer;

import cn.et.test.entity.Food;
import cn.et.test.service.LuceService;
@RestController
public class IndexDemo {
	
	@Autowired
	LuceService ls;
	static String drc="E:\\index";
	//定义存储目录
	static Analyzer aly= new IKAnalyzer();
	//搜索
	@GetMapping("/solr")
	public String search(String foodname) throws Exception {
		Directory dr= FSDirectory.open(new File(drc));
		//读取存储目录
		DirectoryReader ird=DirectoryReader.open(dr);
		//搜索类
		IndexSearcher isearcher=new IndexSearcher(ird);
		//Lucene查询解析 用于指定查询的属性名和分词器
		QueryParser parser = new QueryParser(Version.LUCENE_47,"Food", aly);
		//开始搜索
		Query query=parser.parse(foodname);
		//获取搜索的结果指定返回的docuemnt个数
		ScoreDoc[] hits= isearcher.search(query, null, 10).scoreDocs;
		String Foodanme="";
		for(int i=0;i<hits.length;i++){
			//获取单独的document
			Document hitDoc = isearcher.doc(hits[i].doc);
			Foodanme=hitDoc.getField("Food").stringValue()+"<br/>";
		}
			ird.close();
			dr.close();
			return Foodanme;
			
	}
	
	//创建索引库
	@GetMapping("/writer")
	public void write() throws IOException{
		//索引库的存储目录
		Directory dr= FSDirectory.open(new File(drc));
		//管联Lucene版本和当前分词器
		IndexWriterConfig cfi= new IndexWriterConfig(Version.LUCENE_47,aly);
		//传入目录和分词器
		IndexWriter iwriter = new IndexWriter(dr,cfi);
		//获取数据库里的数据
		List<Food> lt= ls.query();
		for(Food f:lt){
			//document对象Field属性
			Document doc= new Document();
			//TextField.TYPE_STORED 写入存储目录
			Field field= new Field("Food",f.getFoodname(),TextField.TYPE_STORED);
			doc.add(field);
			 //写入存储目录
			 iwriter.addDocument(doc);
		}
		 iwriter.commit();
		 iwriter.close();
	}
}
